package com.luyou.awt.canvas;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Random;

/**
 * 绘图
 */
public class SimpleDrawTest {

    private final String RECT_SHAPE = "rect";

    private final String OVAL_SHAPE = "oval";

    private Frame frame = new Frame("绘图");

    private Button rect = new Button("绘制矩形");

    private Button oval = new Button("绘制原型");

    private MyCanvas draArea = new MyCanvas();

    //绘制图形变量
    private String shape;

    public void init(){
        Panel panel = new Panel();
        rect.addActionListener(e -> {
            shape = RECT_SHAPE;
            draArea.repaint();
        });
        oval.addActionListener(e -> {
            shape = OVAL_SHAPE;
            draArea.repaint();
        });
        panel.add(rect);
        panel.add(oval);

        draArea.setPreferredSize(new Dimension(250, 180));
        frame.add(draArea);
        frame.add(panel, BorderLayout.SOUTH);
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        frame.pack();
        frame.setVisible(true);

    }

    public static void main(String[] args) {
        new SimpleDrawTest().init();
    }




    private class MyCanvas  extends Canvas{

        @Override
        public void paint(Graphics g) {
            if(shape == null){
                return;
            }
            Random random = new Random();
            if(shape.equals(RECT_SHAPE)){
                g.setColor(new Color(220, 180, 80));
                g.drawRect(random.nextInt(200), random.nextInt(120), 40, 60);
            }
            if(shape.equals(OVAL_SHAPE)){
                g.setColor(new Color(80, 100, 200));
                g.drawOval(random.nextInt(200), random.nextInt(120), 50, 40);
                //填充颜色
//                g.fillOval(random.nextInt(200), random.nextInt(120), 50, 40);
            }
        }
    }
}
